package com.yilin.tms.order.service.payment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.MathUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.order.clearing.ClearingDetail;
import com.yilin.tms.core.entity.order.payment.ServicePaymentCost;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.order.mapper.payment.ServicePaymentCostMapper;
import com.yilin.tms.order.service.payment.IServicePaymentCostService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * 上级服务费用单
 * 上级平台收取下级平台费用
 */
@Service
@Transactional
public class ServicePaymentCostService  extends ServiceImpl<ServicePaymentCostMapper, ServicePaymentCost> implements IServicePaymentCostService {

    @Resource
    ServicePaymentCostMapper servicePaymentCostMapper;
    @Resource
    IUserRemote userRemote;
    /**
     * 通知支付结果，重复通知无效
     * 通知结果只更新状态
     */
    @Override
    public void updateServicePaymentResult(Account loginUser,TradeRecord tradeRecord) {
        List<TradeRecord.TradeStatus> statusList = ArrayUtil.initList(TradeRecord.TradeStatus.paySuccess, TradeRecord.TradeStatus.payFail, TradeRecord.TradeStatus.create, TradeRecord.TradeStatus.close);
        if (!statusList.contains(tradeRecord.getTradeStatus())) throw new BusinessException("服务支付结果状态有误！");
        String[] servicePaymentIds = tradeRecord.getOrderPaymentIds().split(",");
        List<ServicePaymentCost> servicePaymentCostList = servicePaymentCostMapper.selectBatchIds(ArrayUtil.initList(servicePaymentIds));
        for (ServicePaymentCost servicePaymentCost : servicePaymentCostList) {
            if (servicePaymentCost.getPayStatus() == ServicePaymentCost.PayStatus.success) throw new BusinessException("订单已经支付完成...");
            /// 分别在成功，创建，关闭+失败时更新状态
            if (tradeRecord.getTradeStatus() == TradeRecord.TradeStatus.paySuccess) {
                servicePaymentCost.setBankFlowNo(tradeRecord.getBankFlowNo());
                servicePaymentCost.setPayCompleteTime(new Date());
                servicePaymentCost.setPaymentTypeName(tradeRecord.getPayType().name+tradeRecord.getBankType().name);
                servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.success);
                servicePaymentCost.setPaymentCapitalAccount(tradeRecord.getPaymentCapitalAccount());
                servicePaymentCost.setIncomeCapitalAccount(tradeRecord.getIncomeCapitalAccount());
                servicePaymentCost.setOptUserId(tradeRecord.getOptUserId());
                servicePaymentCost.setOptUserName(tradeRecord.getOptUserName());
                servicePaymentCost.setBankFlowNo(tradeRecord.getBankFlowNo());
            } else if (tradeRecord.getTradeStatus() == TradeRecord.TradeStatus.create) {
                servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.wait);
                servicePaymentCost.setInitiateUserId(loginUser == null ? null : loginUser.getId());
                servicePaymentCost.setInitiateUserName(loginUser == null ? null : loginUser.getName());
                servicePaymentCost.setTradeNo(tradeRecord.getTradeNo());
            } else {//失败/关闭时，恢复预支付单状态
                servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.approved);
                servicePaymentCost.setTradeNo(null);
            }
            servicePaymentCostMapper.updateById(servicePaymentCost);
        }
    }

    /**
     * 生成运营费用单
     * 基于清算明细生成
     */
    @Override
    public ServicePaymentCost generateServicePayment(ServicePaymentCost.ServicePlatType platType, ClearingDetail clearingDetail) {
        ServicePaymentCost servicePaymentCost = getServicePaymentCostBySourceOrderId(platType, clearingDetail.getId());
        if (servicePaymentCost != null) return servicePaymentCost;
        //-创建信息支付单
        servicePaymentCost = new ServicePaymentCost();
        servicePaymentCost.setServicePlatType(platType);
        if (platType == ServicePaymentCost.ServicePlatType.fhPlat) {
//            servicePaymentCost.setServicePlatId(clearingDetail.getZonePlatId());
//            servicePaymentCost.setServicePlatName(clearingDetail.getZonePlatName());
//            Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(clearingDetail.getZonePlatId()));
//            servicePaymentCost.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
//            servicePaymentCost.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());

            servicePaymentCost.setOperateFee(clearingDetail.getZoneOperateFee());
            servicePaymentCost.setTechnicalFee(clearingDetail.getZoneTechnicalFee());
        } else {
//            servicePaymentCost.setServicePlatId(clearingDetail.getPlatId());
//            servicePaymentCost.setServicePlatName(clearingDetail.getPlatName());
//            Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(clearingDetail.getPlatId()));
//            servicePaymentCost.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
//            servicePaymentCost.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());

            servicePaymentCost.setOperateFee(clearingDetail.getPlatOperateFee());
            servicePaymentCost.setTechnicalFee(clearingDetail.getPlatTechnicalFee());
        }

        servicePaymentCost.setServiceCost(MathUtil.round(MathUtil.add(servicePaymentCost.getOperateFee(),servicePaymentCost.getTechnicalFee()),2));

        servicePaymentCost.setSourceOrderId(clearingDetail.getId());
        servicePaymentCost.setPrePaymentNo(DateTimeUtil.dateNo("YF"));
        servicePaymentCost.setSourceOrderNo(clearingDetail.getClearingOrderNo());

        // 司机在扣款前应得费用，不是实付费用
        servicePaymentCost.setPayCreateTime(new Date());
        servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.approved);
        if (servicePaymentCost.getServicePlatName().contains("(全国)")){
            servicePaymentCost.setServicePlatName(servicePaymentCost.getServicePlatName().split("(全国)")[0]);
        }
        if (servicePaymentCost.getServicePlatName().contains("(孵化)")){
            servicePaymentCost.setServicePlatName(servicePaymentCost.getServicePlatName().split("(孵化)")[0]);
        }
        if (servicePaymentCost.getServicePlatName().contains("(网货)")){
            servicePaymentCost.setServicePlatName(servicePaymentCost.getServicePlatName().split("(网货)")[0]);
        }
        if (servicePaymentCost.getServicePlatName().equals(servicePaymentCost.getSuperiorPlatName())){
            servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.success);
        }
        servicePaymentCostMapper.insert(servicePaymentCost);
        return servicePaymentCost;
    }

//    /**
//     * 生成技术费用单
//     * 基于交易记录生成
//     */
//    @Override
//    public ServicePaymentCost generateServicePayment(ServicePaymentCost.ServicePlatType platType, TradeRecord tradeRecord) {
//        ServicePaymentCost servicePaymentCost = getServicePaymentCostBySourceOrderId(platType, tradeRecord.getId());
//        if (servicePaymentCost != null) return servicePaymentCost;
//        //-创建信息支付单
//        servicePaymentCost = new ServicePaymentCost();
//        servicePaymentCost.setServicePlatType(platType);
//        servicePaymentCost.setServiceFeeType(ServicePaymentCost.ServiceFeeType.technicalFee);
//        if (platType == ServicePaymentCost.ServicePlatType.fhPlat) {
//            servicePaymentCost.setServicePlatId(tradeRecord.getZonePlatId());
//            servicePaymentCost.setServicePlatName(tradeRecord.getZonePlatName());
//            Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(tradeRecord.getZonePlatId()));
//            servicePaymentCost.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
//            servicePaymentCost.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
//            servicePaymentCost.setServiceCost(tradeRecord.getZoneTechnicalFee());
//        } else {
//            servicePaymentCost.setServicePlatId(tradeRecord.getPlatId());
//            servicePaymentCost.setServicePlatName(tradeRecord.getPlatName());
//            Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(tradeRecord.getPlatId()));
//            servicePaymentCost.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
//            servicePaymentCost.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
//            servicePaymentCost.setServiceCost(tradeRecord.getPlatTechnicalFee());
//        }
//        servicePaymentCost.setSourceOrderId(tradeRecord.getId());
//        servicePaymentCost.setPrePaymentNo(DateTimeUtil.dateNo("YF"));
//        servicePaymentCost.setSourceOrderNo(tradeRecord.getTradeNo());
//
//        // 司机在扣款前应得费用，不是实付费用
//        servicePaymentCost.setPayCreateTime(new Date());
//        servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.approved);
//        if (servicePaymentCost.getServicePlatName().equals(servicePaymentCost.getSuperiorPlatName())){
//            servicePaymentCost.setPayStatus(ServicePaymentCost.PayStatus.success);
//        }
//        servicePaymentCostMapper.insert(servicePaymentCost);
//        return servicePaymentCost;
//    }

    @Override
    public ServicePaymentCost getServicePaymentCostBySourceOrderId(ServicePaymentCost.ServicePlatType servicePlatType, String sourceOrderId) {
        QueryWrapper<ServicePaymentCost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("source_order_id", sourceOrderId);
        queryWrapper.eq("service_plat_type", servicePlatType.index);
        return servicePaymentCostMapper.selectOne(queryWrapper);
    }

    @Override
    public List<ServicePaymentCost> getServicePaymentListByIds(List<String> servicePaymentIds) {
        return servicePaymentCostMapper.selectBatchIds(servicePaymentIds);
    }

    @Override
    public PageData<ServicePaymentCost> getServicePaymentCostPage(ServicePaymentCost query, Account loginUser, Integer page, Integer limit) {
        QueryWrapper<ServicePaymentCost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("service_plat_id", loginUser.getOrganizeId());
        return servicePaymentCostMapper.selectPage(new PageData<>(page, limit), QueryUtil.andQueryWrapper(queryWrapper, query));
    }

}
